<?php
/**
 * Session登录验证类
 */
class SessionAuth {
    private $sessionKey = 'user_auth';
    
    public function __construct() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    }
    
    /**
     * 用户登录验证
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $captcha 验证码
     * @return array 返回验证结果
     */
    public function login($username, $password, $captcha) {
        // 默认管理员账号
        $defaultUser = 'admin';
        $defaultPass = 'admin';
        $defaultCaptcha = '1234';
        
        // 验证输入
        if (empty($username) || empty($password) || empty($captcha)) {
            return ['success' => false, 'message' => '请填写完整的登录信息'];
        }
        
        // 验证账号密码和验证码
        if ($username === $defaultUser && $password === $defaultPass && $captcha === $defaultCaptcha) {
            // 登录成功，设置session
            $_SESSION[$this->sessionKey] = [
                'username' => $username,
                'login_time' => time(),
                'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
            ];
            
            return ['success' => true, 'message' => '登录成功'];
        } else {
            // 登录失败
            $errors = [];
            if ($username !== $defaultUser) {
                $errors[] = '用户名错误';
            }
            if ($password !== $defaultPass) {
                $errors[] = '密码错误';
            }
            if ($captcha !== $defaultCaptcha) {
                $errors[] = '验证码错误';
            }
            
            return ['success' => false, 'message' => '登录失败: ' . implode(', ', $errors)];
        }
    }
    
    /**
     * 检查用户是否已登录
     * @return bool
     */
    public function isLoggedIn() {
        return isset($_SESSION[$this->sessionKey]);
    }
    
    /**
     * 获取当前登录用户信息
     * @return array|null
     */
    public function getCurrentUser() {
        return $this->isLoggedIn() ? $_SESSION[$this->sessionKey] : null;
    }
    
    /**
     * 用户登出
     */
    public function logout() {
        unset($_SESSION[$this->sessionKey]);
        session_destroy();
    }
    
    /**
     * 获取登录状态信息
     * @return array
     */
    public function getLoginStatus() {
        if ($this->isLoggedIn()) {
            $user = $this->getCurrentUser();
            return [
                'logged_in' => true,
                'username' => $user['username'],
                'login_time' => date('Y-m-d H:i:s', $user['login_time']),
                'ip' => $user['ip']
            ];
        } else {
            return [
                'logged_in' => false,
                'message' => '用户未登录'
            ];
        }
    }
}



